In [1]:
import matplotlib.pyplot as plt
import numpy as np

# For presentation purposes only.
%matplotlib inline

Plotting Matrices

At some point you may need to plot a matrix. This works a bit differently from regular plots.


In [2]:
def create_matrix(size):
    mat = np.zeros((size, size))
    for i in range(size):
        for j in range (size):
            mat[i, j] = i * j
    return mat

create_matrix(4)


Out[2]:
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  1.,  2.,  3.],
       [ 0.,  2.,  4.,  6.],
       [ 0.,  3.,  6.,  9.]])

In [3]:
mat = create_matrix(20)

plt.imshow(mat)
plt.colorbar() # Adds a colorbar to the plot to aid in interpretation.
plt.xlabel("x")
plt.ylabel("y")
plt.title("Matrix Plot")


Out[3]:
<matplotlib.text.Text at 0x7f4e79c78650>

In the plot above each cell of the matrix corresponds to one of the coloured grids, with the colour indicating the cell value.


In [4]:
mat = create_matrix(20)

plt.imshow(mat, interpolation="spline16")
plt.colorbar() 
plt.xlabel("x")
plt.ylabel("y")
plt.title("Matrix Plot")


Out[4]:
<matplotlib.text.Text at 0x7f4e79b22cd0>

It's possible to smooth the plot by utilizing interpolation. This isn't something that I would recommend though as it hides the structure of your data. Note however that this USED to be the default behaviour of the implot function in earlier versions of Matplotlib.

Increasing the sampling density is a better way of generating a nicer plot.


In [5]:
mat = create_matrix(60)
plt.imshow(mat)
plt.colorbar()
plt.xlabel("x")
plt.ylabel("y")
plt.title("Denser Matrix Plot")


Out[5]:
<matplotlib.text.Text at 0x7f4e79987550>

The color scale used to represent the data can also be modified using the cmap keyword argument.


In [6]:
import matplotlib.cm as cm

plt.imshow(mat, cmap=cm.Reds)
plt.colorbar()
plt.xlabel("x")
plt.ylabel("y")
plt.title("Switching Color Scale ")


Out[6]:
<matplotlib.text.Text at 0x7f4e7983ef10>

There are lots of different colormaps to choose from.


In [7]:
plt.imshow(mat, cmap=cm.winter_r)
plt.colorbar()
plt.xlabel("x")
plt.ylabel("y")
plt.title("Switching Color Scale ")


Out[7]:
<matplotlib.text.Text at 0x7f4e7971d910>